package com.link.base.base.enterprise.service;

import com.link.base.basic.dao.mybatis.mapper.BasicCommonMapper;
import com.link.base.basic.model.ListOfValue;
import com.link.base.base.enterprise.model.Enterprise;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.appduty.dao.mybatis.mapper.AppDutyMenuInterMapper;
import com.link.base.base.appduty.dao.mybatis.mapper.AppMenuMapper;
import com.link.base.base.appduty.model.AppDutyMenuInter;
import com.link.base.base.appduty.model.AppMenu;
import com.link.base.base.common.dao.mybatis.mapper.ImageMapper;
import com.link.base.base.common.model.Image;
import com.link.base.base.duty.model.DutyMenu;
import com.link.base.base.enterprise.dao.mybatis.mapper.EnterpriseMapper;
import com.link.base.base.enterprise.model.PartTable;
import com.link.base.base.invloc.model.Invloc;
import com.link.base.base.invloc.service.InvlocService;
import com.link.base.base.orgnization.dao.mybatis.mapper.OrgnizationMapper;
import com.link.base.base.orgnization.model.Orgnization;
import com.link.base.base.position.dao.mybatis.mapper.PositionMapper;
import com.link.base.base.position.model.Position;
import com.link.base.base.product.model.PriceList;
import com.link.base.base.product.service.PriceListService;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.database.DataSource;
import com.link.core.basic.database.DataSourceType;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.model.CallParam;
import com.link.core.basic.model.UploadImgInfo;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.apache.commons.io.FileUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 企业管理
 *
 * @author 阳晓琳
 * @date 2019/12/12 update
 */
@Service
public class EnterpriseServiceImpl extends BasicServiceImpl<Enterprise> implements EnterpriseService {

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private ImageMapper service;

    @Resource
    private UserService userService;

    @Resource
    private PriceListService priceListService;
    @Resource
    private AccountService accountService;

    @Resource
    private InvlocService invlocService;

    @Resource
    private BasicCommonMapper basicCommonMapper;

    @Resource
    private OrgnizationMapper orgnizationMapper;

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private AppMenuMapper appMenuMapper;

    @Resource
    private AppDutyMenuInterMapper appDutyMenuInterMapper;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public BasicMapper<Enterprise> getBasicMapper() {
        return enterpriseMapper;
    }

    /**
     * 校验手机号
     */
    private static final Pattern PATTERN = Pattern.compile("^((13[0-9])|(14[5,7,9])|(15[^4,\\D])|(17[0,1,3,5-8])|(18[0-9]))\\d{8}$");

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void initializeCompany(CallParam record) throws ServiceException {
        try {
            enterpriseMapper.initializeCompany(record);
            System.err.println(record.getReturnStatus());
            System.err.println(record.getMsgData());
            String ok = "OK";
            if (!StringUtils.equals(ok, record.getReturnStatus())) {
                throw new ServiceException(record.getMsgData());
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    private void setNewCorpLov(CallParam record) throws Exception {
//        KeyGenerateUtil keyGenerateUtil = KeyGenerateUtil.getInstance(jdbcTemplate);
        //删除该账套下所有值列表
        enterpriseMapper.deleteAllListOfVal(record);
        //复制000账套下的所有值列表至当前账套
        ListOfValue lov = new ListOfValue();
        lov.setCorpid(record.getParam1());
        List<ListOfValue> insertList = new ArrayList<>();
        /*List<EnterLov> enterLovList = enterpriseMapper.queryCorpLovList(lov);*/
        List<ListOfValue> noParList = enterpriseMapper.queryNoParValList(lov);
        /*List<String> idList = keyGenerateUtil.generateIdListBySize(2000);*/
        BasicModel user = UserUtil.getUser();
        for (ListOfValue lovRecord : noParList) {
            lovRecord.setAttr1(String.valueOf(lovRecord.getId()));
//            lovRecord.setId(keyGenerateUtil.getGenerateRowId());
            lovRecord.setId(keyGenerateDao.keyGenerate());
            lovRecord.setCreatedBy(user.getId());
            lovRecord.setLastUpdatedBy(user.getId());

            lovRecord.setCorpid(record.getParam1());
            /*basicCommonMapper.insert(lovRecord);*/
            insertList.add(lovRecord);
            //查询并复制所有子值列表
            if (!StringUtils.isBlank(lovRecord.getAttr2())) {
                copyChildListOfValue(lovRecord,insertList);
            }
        }
        Integer num = 500 ;
        Integer count = insertList.size() / num;
        for (int i = 0; i < count + 1 ; i ++) {
            if (i == count) {
                enterpriseMapper.insertListOfValue(insertList.subList(i * num,insertList.size()));
            } else {
                enterpriseMapper.insertListOfValue(insertList.subList(i * num,(i + 1) * num));
            }
        }
        //enterpriseMapper.insertListOfValue(insertList);
    }

    private void setBasicValues(CallParam record) throws Exception {
        //为账套设立默认组织
        Orgnization orgnization = new Orgnization();
        orgnization.setCorpid(record.getParam1());
        orgnizationMapper.deleteCorpOrg(orgnization);
        //获取000账套下的默认组织
        orgnizationMapper.insertCorpOrg(record);
        //为账套设立默认职位
        Position position = new Position();
        position.setCorpid(record.getParam1());
        //删除当前账套下所有职位
        positionMapper.deleteCorpPosition(position);
        positionMapper.insertCorpPosition(record);
        //插入用户职位中间表
        enterpriseMapper.deleteUserPostn(record);
        record.setId(keyGenerateDao.keyGenerate());
        enterpriseMapper.insertUserPostn(record);
        //默认职责
        enterpriseMapper.deleteCorpDuty(record);
        enterpriseMapper.insertCorpDuty(record);
        //插入用户职责
        enterpriseMapper.deleteUserDuty(record);
        record.setId(keyGenerateDao.keyGenerate());
        enterpriseMapper.insertUserDuty(record);
        //新建app职责
        enterpriseMapper.deleteAppRole(record);
        Long empId = keyGenerateDao.keyGenerate();
        record.setId(empId);
        enterpriseMapper.insertAppRole(record);
        //分配职责视图
        enterpriseMapper.deleteDutyMenu(record);
        List<DutyMenu> dutyMenuList = enterpriseMapper.queryDutyMenu(record);
        if (dutyMenuList != null && dutyMenuList.size() > 0) {
            for (DutyMenu dMenu : dutyMenuList) {
                dMenu.setId(keyGenerateDao.keyGenerate());
            }
            enterpriseMapper.insertDutyMenuList(dutyMenuList);
        }
        //复制000全套app菜单
        enterpriseMapper.deleteAppRoleAuth(record);
        List<AppMenu> appMenuList = appMenuMapper.queryCorpAppMenu(record);
        if (appMenuList != null && appMenuList.size() > 0) {
            for (AppMenu aMenu : appMenuList) {
                aMenu.setId(keyGenerateDao.keyGenerate());
            }
            appMenuMapper.insertAppMenuList(appMenuList);
        }
        //复制app职责下菜单
        enterpriseMapper.deleteAppRoleMenu(record);
        record.setAttr6(String.valueOf(empId));
        List<AppDutyMenuInter> appDutyMenuList = appDutyMenuInterMapper.queryCorpAppDutyMenu(record);
        if (appDutyMenuList != null && appDutyMenuList.size() > 0) {
            for (AppDutyMenuInter appDutyMenu : appDutyMenuList) {
                appDutyMenu.setId(keyGenerateDao.keyGenerate());
            }
            appDutyMenuInterMapper.insertAppDutyMenuList(appDutyMenuList);
        }
        enterpriseMapper.updateAppRoleMenu(record);
    }

    /**
     * 删除企业
     *
     * @throws ServiceException
     */
    @Override
    public void deleteCompany(CallParam record) throws Exception {
        enterpriseMapper.deleteCompany(record);
    }

    @Override
    @DataSource(DataSourceType.RANDOM)
    public Enterprise queryByCode(Long code) throws Exception {
        if (null == code) {
            throw new ServiceException("ENTER-001");
        }
        Enterprise queryEp = new Enterprise();
        queryEp.setCode(code);
        queryEp.setPageFlag(false);
        List<Enterprise> list = queryByExamplePage(queryEp);
        if (list == null || list.size() == 0) {
            throw new ServiceException("ENTER-002");
        } else if (list.size() > 1) {
            throw new ServiceException("ENTER-003");
        }
        Enterprise enterprise = list.get(0);
        return enterprise;
    }

    @Override
    @DataSource(DataSourceType.RANDOM)
    public Enterprise queryByCode(Enterprise enterprise) throws Exception {
        if (null == enterprise.getCode()) {
            throw new ServiceException("ENTER-001");
        }
        enterprise.setPageFlag(false);
        List<Enterprise> list = queryByExamplePage(enterprise);
        if (list == null || list.size() == 0) {
            throw new ServiceException("ENTER-002");
        } else if (list.size() > 1) {
            throw new ServiceException("ENTER-003");
        }
        enterprise = list.get(0);
        return enterprise;
    }

    @Override
    public List<Image> imgUpload(List<MultipartFile> myfiles) throws ServiceException {
        List<Image> list = new ArrayList<Image>();
        CoreUser user = UserUtil.getUser();
        Random random = new Random();
        String realativPath = "/web/enterprise/" + user.getId() + "/" + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss");
        String realPath = YmlConstants.getPortalShareFileDir() + realativPath;
        try {
            for (MultipartFile myfile : myfiles) {
                String originalName = myfile.getOriginalFilename();
                String newfileName = user.getId() + DateUtil.dateToStr(new Date(), "yyyyMMddHHmmss") + random.nextInt(100)
                        + originalName.substring(originalName.lastIndexOf('.'));
                try {
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, newfileName));
                } catch (IOException e) {
                    LCLogger.withException(e);
                    throw new ServiceException(e.getMessage());
                }
                Image img = new Image();
                img.setId(keyGenerateDao.keyGenerate());
                UploadImgInfo ui = ImageUtil.saveImageAndLessImage(realPath + "/" + newfileName, "enterprise", String.valueOf(img.getId()));
                img.setUrl(realativPath + "/" + newfileName);
                img.setSmallurl(ui.getFileLessHtppPath());
                img.setBigurl(ui.getBigfileHtppPath());
                img.setAttachmentSize(String.valueOf(myfile.getSize()));
                img.setAttachmentName(newfileName);
                img.setImgdesc("web端上传");
                img.setAttachmentOriginal(originalName);
                img.setAttachmentType(myfile.getContentType());
                service.imageInsert(img);
                list.add(img);
            }
            return list;
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public void qrCodeImageUpate(Enterprise record, List<Image> list) throws ServiceException {
        try {
            for (Image img : list) {
                record.setQrCodeId(img.getId());
                enterpriseMapper.qrCodeImageUpdate(record);
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public void qidianAuthUpdate(Enterprise record) throws Exception {
        List<Enterprise> enterList = queryByAuthAppidPage(record.getAuthAppid());
        boolean flag = (enterList.size() == 1 && !enterList.get(0).getId().equals(record.getId())) ? true : false;
        boolean  sizeFlag = (enterList.size() > 1) ? true : false;
        if (sizeFlag || flag) {
            throw new ServiceException("ENTER-004");
        }
        enterpriseMapper.qidianAuthUpdate(record);
    }

    @Override
    public void authAccessTokenUpdate(Enterprise record) throws Exception {
        enterpriseMapper.authAccessTokenUpdate(record);
    }

    @Override
    public List<Enterprise> queryQidianEnt() throws Exception {
        return enterpriseMapper.queryQidianEnt(new Enterprise());
    }

    @Override
    public List<Enterprise> queryByAuthAppidPage(String authAppid) throws Exception {
        QueryParams qps = new QueryParams();
        qps.setPageFlag(false);
        qps.addFilter(new Filter("authAppid", authAppid));
        Enterprise t = (Enterprise) BasicModel.transformClass(Enterprise.class, qps);
        List<Enterprise> list = enterpriseMapper.queryByExamplePage(t);
        return list;
    }

    @Override
    public String queryQiDianToken() throws Exception {
        CoreUser user = UserUtil.getUser();
        Enterprise enterprise = queryByCode(user.getCorpid());
        return enterprise.getAuthAccessToken();
    }

    @Override
    public String[] loadCorpidsWhichActiveStrictSecurityMode2Redis() {
        String[] corpIds = enterpriseMapper.getCorpidsWhichActiveStrictSeurityMode();
        //RedisConstants.STRICT_SECURITY_CORP_SET_RKEY
        LinkRedisClient j = RedisUtil.getJedis();
        try {
            j.del(RedisConstants.STRICT_SECURITY_CORP_SET_RKEY);
            if (corpIds.length > 0) {
                j.sadd(RedisConstants.STRICT_SECURITY_CORP_SET_RKEY, corpIds);
            }
        } finally {
            RedisUtil.returnResource(j);
        }
        return corpIds;
    }

    /**
     * 更新企业认证图片
     *
     * @param enterprise
     * @throws Exception
     */
    @Override
    public void updateVoucherImg(Enterprise enterprise) throws ServiceException {

        enterprise = Objects.requireNonNull(enterprise);
        Enterprise params = new Enterprise();
        params.setId(enterprise.getId());
        //营业资格证
        if (!StringUtils.isBlank(enterprise.getBusQuaCerBigUrl())
                && !StringUtils.isBlank(enterprise.getBusQuaCerUrl())) {
            params.setBusQuaCerBigUrl(enterprise.getBusQuaCerBigUrl());
            params.setBusQuaCerUrl(enterprise.getBusQuaCerUrl());
        } else if (!StringUtils.isBlank(enterprise.getIdcardBigUrl()) && !StringUtils.isBlank(enterprise.getIdcardFacadeUrl())) {
            //法人代表身份证正面
            params.setIdcardBigUrl(enterprise.getIdcardBigUrl());
            params.setIdcardFacadeUrl(enterprise.getIdcardFacadeUrl());
        } else if (!StringUtils.isBlank(enterprise.getIdcardBackBigUrl()) && !StringUtils.isBlank(enterprise.getIdcardBackUrl())) {
            //法人代表身份证反面
            params.setIdcardBackBigUrl(enterprise.getIdcardBackBigUrl());
            params.setIdcardBackUrl(enterprise.getIdcardBackUrl());
        } else if (!StringUtils.isBlank(enterprise.getOtherBigUrl()) && !StringUtils.isBlank(enterprise.getOtherVoucherUrl())) {
            //其他凭证
            params.setOtherBigUrl(enterprise.getOtherBigUrl());
            params.setOtherVoucherUrl(enterprise.getOtherVoucherUrl());
        } else {
            throw new ServiceException("ENTER-005");
        }
        enterpriseMapper.updateVoucherImg(params);
    }

    @Override
    public Enterprise getEnterpriseInfo(Long code) throws Exception {
        return enterpriseMapper.getEnterpriseInfo(code);
    }

    /**
     * 初始化企业信息
     *
     * @param entity
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void initEnterpriseInfo(Enterprise entity, CallParam callParam) throws Exception {
        User record = new User();
        //删除老用户
        if (!"".equals(entity.getUserId()) && entity.getUserId() != null) {
            record.setId(entity.getUserId());
            userService.deleteById(record);
        }
        User checkUser = userService.getUserByUsername(entity.getUserName());
        if (checkUser != null) {
            throw new ServiceException("ENTER-006",entity.getUserName());
        }
        String mobilePhone = entity.getMobilePhone();
        Matcher m = PATTERN.matcher(mobilePhone);
        if (!m.matches()) {
            throw new ServiceException("PUBLIC-043");
        }
        Long userId = keyGenerateService.keyGenerate();
        entity.setUserId(userId);
        Long postnId = keyGenerateService.keyGenerate();
        Long orgId = keyGenerateService.keyGenerate();
        Long dutyId = keyGenerateService.keyGenerate();
        String password = mobilePhone.substring(mobilePhone.length() - 6, mobilePhone.length());
        String encodedNewPassword = PasswordUtil.generatePwd(password);
        record.setId(userId);
        record.setUsername(entity.getUserName());
        record.setPassword(encodedNewPassword);
        record.setFirstName(entity.getFirstname());
        record.setContactPhone(entity.getMobilePhone());
        //设置企业帐套
        record.setPostnId(postnId);
        record.setOrgId(orgId);
        record.setDutyId(dutyId);
        record.setCorpid(entity.getCode());
        record.setAppResp(entity.getAppDutyName());

        PriceList priceList = new PriceList();
        Long priceListId = keyGenerateService.keyGenerate();
        priceList.setId(priceListId);
        priceList.setOrgId(orgId);
        priceList.setPostnId(postnId);
        priceList.setCorpid(entity.getCode());

        entity.setDefaultPrice(priceListId);
        callParam.setParam1(entity.getCode());
        callParam.setParam2(String.valueOf(entity.getCrmDutyId()));
        callParam.setParam3(String.valueOf(entity.getAppDutyId()));
        CoreUser user = UserUtil.getUser();
        callParam.setParam4(String.valueOf(user.getId()));
        callParam.setParam5(String.valueOf(postnId));
        callParam.setParam6(String.valueOf(orgId));
        callParam.setAttr1(String.valueOf(dutyId));
        callParam.setAttr2(String.valueOf(userId));
        /*this.initializeCompany(callParam);*/
        //java版初始化企业
        initializeCompanyNoCall(callParam);
        String ok = "OK";
        if (ok .equals(callParam.getReturnStatus())) {
            //初始化品牌商客户
            Account accnt = new Account();
            Long accntId = keyGenerateService.keyGenerate();
            accnt.setPostnId(postnId);
            accnt.setOrgId(orgId);
            accnt.setPriceListId(priceListId);
            accnt.setId(accntId);
            //初始化客户、仓库、用户和价格表
            setNewAccountAndInvLocAndUser(accnt,entity,record,priceList);
            entity.setvAcctId(accntId);
            entity.setRegisterStatus("Y");
            entity.setRegisterDate(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            //更新企业管理初始化新建的用户ID
            this.update(entity);
        } else {
            throw new ServiceException(callParam.getMsgData());
        }
    }

    private void setNewAccountAndInvLocAndUser(Account accnt, Enterprise entity, User record, PriceList priceList) throws Exception {
        accnt.setCorpid(entity.getCode());
        //客户名称和企业名称一致
        accnt.setAcctName(entity.getName());
        accnt.setProvince(entity.getProvince());
        accnt.setCity(entity.getCity());
        accnt.setDistrict(entity.getCounty());
        //详细地址
        accnt.setAddress(entity.getDetailedAddress());
        //品牌商
        accnt.setAcctType("Vendor");
        //开启对账单 否
        accnt.setAccntStatementFlag("N");
        //状态 有效
        accnt.setAcctStatus("Y");
        //初始化虚拟仓库
        Invloc newInvloc = new Invloc();
        Long invId = keyGenerateService.keyGenerate();
        newInvloc.setId(invId);
        newInvloc.setInvlocName("默认虚拟仓库");
        //值列表的独立源代码
        newInvloc.setInvlocType("FICTITIOUS");
        newInvloc.setOwnerId(accnt.getId());
        newInvloc.setOwnerName(accnt.getAcctName());
        newInvloc.setCorpid(entity.getCode());
        newInvloc.setOrgId(accnt.getOrgId());
        newInvloc.setOrgName(accnt.getOrgName());
        //品牌商客户的默认值
        record.setRole("REGION_SALER");
        record.setStatus("NORMAL");
        record.setEmpType("VendorEmployee");
        record.setScancardFlag("N");
        record.setEmail("administrator@hand-china.com");
        record.setAppRole("Boss");
        //价格表的默认值
        priceList.setActivated("N");
        priceList.setPriceListName("默认价格表-" + entity.getCode());
        accountService.insert(accnt);
        invlocService.insert(newInvloc);
        userService.insert(record);
        priceListService.insert(priceList);
    }

    /***
     * 企业对账单参数开启状态更新
     * @param enterprise
     *   企业对象下的
     *   billStatementFlag 必输
     *   id 必输
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateBillStatementParam(Enterprise enterprise) throws Exception {
        enterpriseMapper.updateBillStatementParam(enterprise);
    }

    /**
     * 定时调度下 查找开启企业对账单开关的企业
     *
     * @param enterprise
     * @return List
     * @throws Exception
     */
    @Override
    public List<Enterprise> queryAllByAssCondition(Enterprise enterprise) throws Exception {
        return enterpriseMapper.queryAllByAssCondition(enterprise);
    }

    @Override
    public List<Enterprise> getEnterpriseByUserCode(Enterprise enterprise) {
        return enterpriseMapper.getEnterpriseByUserCode(enterprise);
    }

    public void copyChildListOfValue(ListOfValue entity,List<ListOfValue> insertList) throws Exception {
        //查询是否有子值列表
        List<ListOfValue> childList = enterpriseMapper.queryChildListByParVal(entity);
        if (childList != null && childList.size() > 0) {
            //遍历循环所有子孙值列表
            for (ListOfValue lov : childList) {
                lov.setAttr1(String.valueOf(lov.getId()));
                lov.setId(keyGenerateDao.keyGenerate());
                lov.setParentId(entity.getId());
                lov.setCorpid(entity.getCorpid());

                lov.setCreatedBy(entity.getCreatedBy());
                lov.setLastUpdatedBy(entity.getLastUpdatedBy());
                /*basicCommonMapper.insert(lov);*/
                insertList.add(lov);
                if (!StringUtils.isBlank(lov.getAttr2())) {
                    copyChildListOfValue(lov, insertList);
                }
            }
        }
    }

    private void initializeCompanyNoCall(CallParam record) {
        try {
            if (null == record.getParam1()) {
                throw new ServiceException("PUBLIC-044");
            }
            String database = "mysql";
            //为新corp_id建立分区
            if (database.equals(YmlConstants.getApplicationDatabase())) {
                //查询现有分区表
                PartTable partTable = new PartTable();
                List<PartTable> partTableList = enterpriseMapper.queryExistPartTable(partTable);
                if (partTableList != null && partTableList.size() > 0) {
                    for (PartTable entity : partTableList) {
                        entity.setColName("CORP_ID");
                        entity.setPartialVal(String.valueOf(record.getParam1()));
                        //是否是分区表
                        PartTable countOne = enterpriseMapper.queryCountPart(entity);
                        if (countOne == null) {
                            throw new ServiceException("PUBLIC-045");
                        }
                        //是否已存在分区
                        PartTable existOne = enterpriseMapper.queryExistNamePart(entity);
                        if (existOne == null) {
                            existOne = new PartTable();
                            existOne.setExistPartVal(0);
                        }
                        if (countOne.getCountPart() == 0) {
                            throw new ServiceException("PUBLIC-045");
                        } else if (countOne.getCountPart() > 0 && existOne.getExistPartVal() == 1) {
                            System.out.println("该表" + entity.getTableName() + "的分区" + entity.getPartialVal() + "已存在");
                        } else {
                            //获取最大分区
                            PartTable maxOne = enterpriseMapper.queryMaxPart(entity);
                            if (maxOne == null) {
                                throw new ServiceException("ENTER-007",entity.getTableName());
                            }
                            String lastPart = maxOne.getLastPartName();
                            String lastPartStr = lastPart.replace("p","");
                            Integer newPartNum = Integer.valueOf(lastPartStr) + 1;
                            entity.setNewPartName("p" + newPartNum);
                            //新增分区
                            enterpriseMapper.addNewPart(entity);
                        }
                    }
                }
            }
            //删除当前corp_id的所有值列表，注意000的账套不做此操作
//            String baseCorp = "000";
            Long baseCorp = 0L;
            if (!baseCorp.equals(record.getParam1())) {
                //复制000账套的值列表到当前账套下
                setNewCorpLov(record);
                //设置默认值
                setBasicValues(record);
                record.setReturnStatus("OK");
            }
        } catch (Exception e) {
            record.setReturnStatus("ERROR");
            record.setMsgData(e.getMessage());
            LCLogger.withException(e);
            throw new ServiceException(e.getMessage());
        }
    }
}
